package com.alibaba.citrus.cr.price.repository.impl;

import com.alibaba.citrus.cr.price.ability.functions.factory.price.process.PropertyProcessManager;
import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.exception.RepositoryException;
import com.alibaba.citrus.cr.price.repository.PriceWriteRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.crforecastsales.domian.pricedimension.dto.CreatePriceDimensionResponse;
import com.epoch.app.crforecastsales.domian.pricedimension.model.PriceDimension;
import com.epoch.app.crforecastsales.domian.pricedimension.service.PriceDimensionService;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.CreatePricePropertyConfigResponse;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdateAllFieldRequest;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdateAllFieldResponse;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdateFeaturesRequest;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdateFeaturesResponse;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdatePriceEndStartRequest;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdatePriceEndStartResponse;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdatePricePropertyConfigForVersionRequest;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.dto.UpdatePricePropertyConfigForVersionResponse;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.model.PricePropertyConfig;
import com.epoch.app.crforecastsales.domian.pricepropertyconfig.service.PricePropertyConfigService;
import com.epoch.app.crforecastsales.domian.pricerecord.dto.CreatePriceRecordResponse;
import com.epoch.app.crforecastsales.domian.pricerecord.dto.QueryPriceRecordByRecordIdRequest;
import com.epoch.app.crforecastsales.domian.pricerecord.dto.QueryPriceRecordByRecordIdResponse;
import com.epoch.app.crforecastsales.domian.pricerecord.dto.UpdatePriceRecordDataForVersionResponse;
import com.epoch.app.crforecastsales.domian.pricerecord.model.PriceRecord;
import com.epoch.app.crforecastsales.domian.pricerecord.service.PriceRecordService;
import com.epoch.app.crforecastsales.domian.pricetype.dto.CreatePriceTypeRequest;
import com.epoch.app.crforecastsales.domian.pricetype.dto.CreatePriceTypeResponse;
import com.epoch.app.crforecastsales.domian.pricetype.service.PriceTypeService;
import com.epoch.app.crpricecenter.sdo.PriceDimensionConfigSDO;
import com.epoch.app.crpricecenter.sdo.PriceDimensionSDO;
import com.epoch.app.crpricecenter.sdo.PriceRecordSDO;
import com.epoch.app.crpricecenter.sdo.PriceTypeSDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author hanguo
 * @date 2021/9/17
 * @Description 价格数据同步 repository
 */
@Repository
public class PriceWriteRepositoryImpl implements PriceWriteRepository {

    @Resource
    private PriceTypeService priceTypeService;

    @Resource
    private PriceRecordService priceRecordService;

    @Resource
    private PricePropertyConfigService pricePropertyConfigService;

    @Resource
    private PriceDimensionService priceDimensionService;

    @Resource
    private PropertyProcessManager propertyProcessManager;

    private static Log log = Log.getLogger(PriceWriteRepositoryImpl.class);

    @Override
    @RepositoryInvoker(remark = "创建价格类型数据", printLog = true, errorCode = "OTS-07-005-01-15-005")
    public Boolean createPriceTypeData(PriceTypeSDO priceTypeSDO) {
        CreatePriceTypeRequest createPriceTypeRequest = new CreatePriceTypeRequest();
        BeanUtils.copyProperties(priceTypeSDO, createPriceTypeRequest);
        createPriceTypeRequest.setIsManual(priceTypeSDO.getManualFlag() ? 1 : 0);
        createPriceTypeRequest.setIsNegativeNumber(priceTypeSDO.getNegativeNumberFlag() ? 1 : 0);
        createPriceTypeRequest.setIsTitle(priceTypeSDO.getTitleFlag() ? 1 : 0);
        createPriceTypeRequest.setDemensionOrder(priceTypeSDO.getDimensionOrder());
        createPriceTypeRequest.setCalculatePattern(priceTypeSDO.getCalculatePattern()==null?null:Integer.parseInt(priceTypeSDO.getCalculatePattern()));
        CreatePriceTypeResponse priceTypeResponse = priceTypeService.createPriceType(createPriceTypeRequest);
        String lastInsertId = priceTypeResponse.getLastInsertId();
        if (StringUtils.isBlank(lastInsertId)) {
            throw new RepositoryException("OTS-07-005-01-15-006");
        }
        return true;
    }

    @Override
    public Result<Boolean> createPriceRecordData(PriceRecordSDO priceRecordSDO) {

        PriceRecord priceRecord = new PriceRecord();
        BeanUtils.copyProperties(priceRecordSDO, priceRecord);
        priceRecord.setMoneyAmount(priceRecordSDO.getMoneyAmount());
        priceRecord.setItemCount(priceRecordSDO.getItemCount() == null ? null : Integer.parseInt(priceRecordSDO.getItemCount().toString()));
        priceRecord.setMoneyPercentage(StringUtils.isBlank(priceRecordSDO.getMoneyPercentage())?null:Integer.parseInt(priceRecordSDO.getMoneyPercentage()));
        priceRecord.setGmtModify(new Date());

        //先查询数据
        QueryPriceRecordByRecordIdRequest queryPriceRecordByRecordIdRequest = new QueryPriceRecordByRecordIdRequest();
        queryPriceRecordByRecordIdRequest.setPriceRecordId(priceRecordSDO.getPriceRecordId());
        QueryPriceRecordByRecordIdResponse queryPriceRecordByRecordIdResponse = priceRecordService.queryPriceRecordByRecordId(queryPriceRecordByRecordIdRequest);

        if (Objects.isNull(queryPriceRecordByRecordIdResponse) ||
                Objects.isNull(queryPriceRecordByRecordIdResponse.getId()) ||
                Objects.isNull(queryPriceRecordByRecordIdResponse.getVersion())) {
            //无数据则执行创建操作
            CreatePriceRecordResponse priceRecordResponse = priceRecordService.createPriceRecord(priceRecord);

            if (Objects.nonNull(priceRecordResponse) && StringUtils.isNotBlank(priceRecordResponse.getLastInsertId())) {
                return Result.success(true);
            }
            log.error("PriceWriteRepositoryImpl_createPriceRecordData_create_fail,价格记录创建失败,价格记录数据" + JSONObject.toJSONString(priceRecordSDO));
        } else {
            //执行更新操作
            priceRecord.setId(queryPriceRecordByRecordIdResponse.getId());
            priceRecord.setVersion(queryPriceRecordByRecordIdResponse.getVersion());
            UpdatePriceRecordDataForVersionResponse updatePriceRecordDataForVersionResponse
                    = priceRecordService.updatePriceRecordDataForVersion(priceRecord);

            if (Objects.nonNull(updatePriceRecordDataForVersionResponse) &&
                    Objects.nonNull(updatePriceRecordDataForVersionResponse.getCount()) &&
                    updatePriceRecordDataForVersionResponse.getCount() > 0) {
                return Result.success(true);
            }

        }

        log.error("PriceWriteRepositoryImpl_createPriceRecordData_update_fail,价格记录更新失败,价格记录数据" + JSONObject.toJSONString(priceRecordSDO));
        return Result.failure(false, "PRICE-", "价格记录数据同步失败");

//        //priceRecord.setFeatures(JSON.toJSONString(features));
//        //先执行更新操作，若存在记录则会返回更新的条数,则不用再执行新增操作
//        UpdatePriceRecordForVersionResponse updatePriceRecordForVersionResponse = priceRecordService.updatePriceRecordForVersion(priceRecord);
//        if(Objects.nonNull(updatePriceRecordForVersionResponse) && updatePriceRecordForVersionResponse.getCount() > 0){
//            return Result.success(true);
//        }



    }

    //todo 韩国      2021/9/24
    @Override
    public Result<Boolean> createPriceDimensionData(PriceDimensionSDO priceDimensionSDO) {
        PriceDimension priceDimension = new PriceDimension();
        BeanUtils.copyProperties(priceDimensionSDO, priceDimension);

        CreatePriceDimensionResponse priceDimensionResponse = priceDimensionService.createPriceDimension(priceDimension);

        String lastInsertId = priceDimensionResponse.getLastInsertId();
        if (StringUtils.isNotBlank(lastInsertId)) {
            return Result.success(true);
        }
        return Result.failure(null, "创建失败");
    }

    //     todo 韩国 2021/9/24
    @Override
    public Result<Boolean> modifyPriceDimension(PriceDimensionSDO priceDimensionSDO) {
        PriceDimension priceDimension = new PriceDimension();
        BeanUtils.copyProperties(priceDimensionSDO, priceDimension);
        Object o = priceDimensionService.updatePriceDimension(priceDimension);
        return null;
    }

    @Override
    @RepositoryInvoker(value = "保存维度配置数据",printLog = true,errorCode = "OTS-07-005-01-15-008")
    public boolean savePriceDimensionConfig(PriceDimensionConfigSDO dimensionConfigSDO) {
        PricePropertyConfig propertyConfig = new PricePropertyConfig();
        /**
         * 维度属性值组成的字符串
         */
        propertyConfig.setDimensionPropertiesGroup(dimensionConfigSDO.getDimensionPropertiesGroup());
        /**
         * 价格开始时间
         */
        propertyConfig.setPriceStartDate(dimensionConfigSDO.getPriceStartDate());
        /**
         * 价格结束时间
         */
        propertyConfig.setPriceEndDate(dimensionConfigSDO.getPriceEndDate());
        /**
         * 价格记录 id
         */
        propertyConfig.setPriceRecordId(dimensionConfigSDO.getPriceRecordId());
        /**
         * 价格类型
         */
        propertyConfig.setPriceTypeId(dimensionConfigSDO.getPriceTypeId());
        /**
         * 维度 id
         */
        propertyConfig.setDimensionId(dimensionConfigSDO.getDimensionId());
        /**
         * 货品 id
         */
        propertyConfig.setItemId(dimensionConfigSDO.getItemId());
        /**
         * 销售组织编码
         */
        propertyConfig.setSalesOrganizationCode(dimensionConfigSDO.getSalesOrganizationCode());
        /**
         * 生成的 md5值
         */
        propertyConfig.setMd5Code(dimensionConfigSDO.getMd5Code());

        /**
         * 租户id
         */
        propertyConfig.setTenantId(dimensionConfigSDO.getTenantId());

        /**
         * 修改时间
         */
        propertyConfig.setGmtModify(new Date());
        propertyConfig.setFeatures(JSONObject.toJSONString(dimensionConfigSDO.getFeaturesMap()));

        propertyConfig.setVersion(1);
        CreatePricePropertyConfigResponse response = pricePropertyConfigService.createPricePropertyConfig(propertyConfig);
        log.info("价格维度配置数据创建 result = {}",JSONObject.toJSONString(response));
        return Objects.nonNull(response) && StringUtils.isNotBlank(response.getLastInsertId());
    }

    /**
     * 更新价格维度配置
     * @param id id
     * @param priceDimensionConfigSDO 价格维度配置 SDO
     * @return
     */
    @Override
    @RepositoryInvoker(value = "更新价格维度配置",printLog = true,errorCode = "OTS-07-005-01-15-009")
    public Boolean updatePriceDimensionConfig(Long id, PriceDimensionConfigSDO priceDimensionConfigSDO) {
        UpdatePricePropertyConfigForVersionRequest request = new UpdatePricePropertyConfigForVersionRequest();
        BeanUtils.copyProperties(priceDimensionConfigSDO, request);
        request.setId(id);
        request.setFeatures(JSONObject.toJSONString(priceDimensionConfigSDO.getFeaturesMap()));

        //防止冗余的features过大数据库报错
        if (request.getFeatures().length() > 1000) {
            request.setFeatures(null);
            log.error("价格维度配置数据冗余过大,超过数据表features字段的1000字符 = {}", priceDimensionConfigSDO.getFeaturesMap());
        }
        UpdatePricePropertyConfigForVersionResponse updatePricePropertyConfigForVersionResponse = pricePropertyConfigService.updatePricePropertyConfigForVersion(request);
        Integer count = updatePricePropertyConfigForVersionResponse.getCount();
        return Objects.nonNull(count) && 1 == count;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean updatePriceDimensionConfigTemp(Long id, PriceDimensionConfigSDO sdo){
        UpdateAllFieldRequest request = new UpdateAllFieldRequest();
        request.setDimensionPropertiesGroup(sdo.getDimensionPropertiesGroup());
        request.setItemId(sdo.getItemId());
        request.setMd5Code(sdo.getMd5Code());
        request.setId(id);

        UpdateAllFieldResponse updateAllFieldResponse = pricePropertyConfigService.updateAllField(request);
        return updateAllFieldResponse.getCount()!=0;
    }

    @Override
    public Boolean updatePriceDimensionConfigFeaturesTemp(Long id, Map<String, String> newMap, Integer version) {
        UpdateFeaturesRequest updateFeaturesRequest = new UpdateFeaturesRequest();
        updateFeaturesRequest.setId(id);
        updateFeaturesRequest.setFeatures(JSONObject.toJSONString(newMap));
        updateFeaturesRequest.setVersion(version);
        UpdateFeaturesResponse updateFeaturesResponse = pricePropertyConfigService.updateFeatures(updateFeaturesRequest);
        return updateFeaturesResponse.getCount() > 0;

    }

    @Override
    public Boolean updatePriceDimensionConfigEndDateTemp(Long id, Date newPriceEndDate,Integer version) {
        UpdatePriceEndStartRequest updatePriceEndStartRequest = new UpdatePriceEndStartRequest();
        updatePriceEndStartRequest.setId(id);
        updatePriceEndStartRequest.setPriceEndDate(newPriceEndDate);
        updatePriceEndStartRequest.setVersion(version);
        UpdatePriceEndStartResponse updatePriceEndStartResponse = pricePropertyConfigService.updatePriceEndStart(updatePriceEndStartRequest);

        return updatePriceEndStartResponse.getCount() > 0;
    }
}
